﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using DunSilverlight.Comm;
using DunLibrary.Dun;
using DunLibrary.Query;
using DunLibrary.Client;

namespace DunSilverlight.Views
{
    /// <summary>
    /// 催款处理
    /// </summary>
    public partial class CollectionTaskDeal : Page
    {
        private const int PageSize = 19;

        private QueryCondition queryCondition = null;

        public CollectionTaskDeal()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(CollectionTaskDeal_Loaded);
        }

        void CollectionTaskDeal_Loaded(object sender, RoutedEventArgs e)
        {
            cmbPeriod.ItemsSource = AppGlobal.Periods;

            AppGlobal.GetBanks((IList<Company> banks) =>
            {
                cmbBank.ItemsSource = banks;
            });
            AppGlobal.GetControlTypes((IList<ControlType> controls) =>
            {
                cmbControlType.ItemsSource = controls;
            });
            LoadCompany();
            LoadOpers();
        }

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        /// <summary>
        /// 通过权限设置界面控制
        /// </summary>
        private void SetControlByRight()
        {

        }
        /// <summary>
        /// 开始查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            BuildHql();
            queryCondition.FirstResult = 0;

            QueryPaging(queryCondition);
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="frist"></param>
        /// <param name="max"></param>
        private void QueryPaging(QueryCondition qc)
        {
            if (qc != null)
            {
                Tools.ShowMask(true);
                CaseService.CaseServiceClient ser = new CaseService.CaseServiceClient();

                ser.GetListByHQLWithPagingCompleted += (object sender, CaseService.GetListByHQLWithPagingCompletedEventArgs e) =>
                {
                    ser.GetCustomDataByHqlCompleted += (object sender1, CaseService.GetCustomDataByHqlCompletedEventArgs e1) =>
                    {
                        try
                        {
                            int total = 0;
                            IList<Case> cases = JsonSerializerHelper.JsonToEntities<Case>(e.Result, out total);

                            dgdCase.ItemsSource = cases;

                            rDataPager1.ItemCount = total;

                            var tb = dgdCase.Columns[3].Footer as TextBlock;
                            if (tb != null)
                                tb.Text = string.Format("{0}", total);

                            double totalAmount = JsonSerializerHelper.JsonToEntity<double>(e1.Result);
                            tb = dgdCase.Columns[8].Footer as TextBlock;
                            if (tb != null)
                                tb.Text = totalAmount.ToString();
                        }
                        catch (Exception ex)
                        {
                            Tools.ShowMessage(ex.Message, "", false);//这里会出错，应该是分页控件的问题
                        }
                        finally
                        {
                            Tools.ShowMask(false);
                            ser.CloseAsync();
                        }
                    };
                    ser.GetCustomDataByHqlAsync(totalAmountHql);

                };

                string condition = Newtonsoft.Json.JsonConvert.SerializeObject(qc);

                ser.GetListByHQLWithPagingAsync(condition);


            }
        }

        //查询符合条件的所有记录的金额总和
        string totalAmountHql = string.Empty;

        /// <summary>
        /// 根据选择条件生成查询的hql
        /// </summary>
        /// <returns></returns>
        private void BuildHql()
        {
            //string hql = "from Case as c inner join c.ArrearRecords as a inner join c.Holder.Contacts as t where c.Catalog.IsFinish=false";
            string hql = "from Case as c where c.Catalog.IsFinish=false";
            string where = null;

            if (!string.IsNullOrEmpty(txtYear.Text.Trim()))
            {
                where = " and c.Year=" + txtYear.Text;//年
            }

            if (cmbPeriod.SelectedItem != null)
            {
                where += " and c.Period=" + cmbPeriod.SelectedItem.ToString();//期
            }

            if (timeImport.SelectedDate != null)
            {
                where += " and year(c.Catalog.ImportTime)*10000+month(c.Catalog.ImportTime)*100+day(c.Catalog.ImportTime)=" + timeImport.SelectedDate.Value.ToString("yyyyMMdd");
            }

            if (cmbBank.SelectedItem != null)//银行
            {
                DunLibrary.Client.Company bank = cmbBank.SelectedItem as DunLibrary.Client.Company;
                where += " and c.Bank.Id=" + bank.Id;
            }

            if (!string.IsNullOrEmpty(txtBranch.Text.Trim()))
            {
                where += string.Format(" and exists (from ArrearRecord as a where a.Case.Id=c.Id and a.BranchName Like '{0}%')", txtBranch.Text.Trim());
                //where += " and a.BranchName='" + txtBranch.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtCardType.Text.Trim()))
            {
                where += string.Format(" and exists (from ArrearRecord as a where a.Case.Id=c.Id and a.Card.CardType = '{0}')", txtBranch.Text.Trim());
                //where += " and a.Card.CardType='" + txtBranch.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtAccount.Text.Trim()))
            {
                where += string.Format(" and exists (from ArrearRecord as a where a.Case.Id=c.Id and a.Card.AccountNo = '{0}')", txtAccount.Text.Trim());
                //where += " and a.Card.AccountNo='" + txtAccount.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtHolder.Text.Trim()))
            {
                where += " and c.Holder.Name='" + txtHolder.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtIdCard.Text.Trim()))
            {
                where += " and c.Holder.Number='" + txtIdCard.Text.Trim() + "'";
            }

            if (!string.IsNullOrEmpty(txtPhone.Text.Trim()))
            {
                where += string.Format(" and exists (from CardholderContact as hc where hc.Owner.Id=c.Holder.Id and hc.Content Like '{0}%')", txtPhone.Text.Trim());
                //where += " and t.Content like '" + txtPhone.Text.Trim() + "%'";
            }

            if (!string.IsNullOrEmpty(txtMinArrear.Text.Trim()))
            {
                double d1 = 0;
                if (double.TryParse(txtMinArrear.Text.Trim(), out d1))
                {
                    where += " and c.TotalAmount >=" + d1;
                }
            }

            if (!string.IsNullOrEmpty(txtMaxArrear.Text.Trim()))
            {
                double d1 = 0;
                if (double.TryParse(txtMaxArrear.Text.Trim(), out d1))
                {
                    where += " and c.TotalAmount <=" + d1;
                }
            }



            if (!string.IsNullOrEmpty(txtCardDelayLevel1.Text.Trim()))
            {
                where += string.Format(" and c.CardDelayLevel >= '{0}' ", txtCardDelayLevel1.Text.Trim());
            }
            if (!string.IsNullOrEmpty(txtCardDelayLevel2.Text.Trim()))
            {
                where += string.Format(" and c.CardDelayLevel <= '{0}' ", txtCardDelayLevel2.Text.Trim());
            }

            //if (!string.IsNullOrEmpty(txtCardDelayLevel1.Text.Trim()))
            //{
            //    where += string.Format(" and exists (from CardholderContact as hc where hc.Owner.Id=c.Holder.Id and a.CardDelayLevel <= '{0}')", txtCardDelayLevel.Text.Trim());
            //    //where += " and a.CardDelayLevel <='" + txtCardDelayLevel1.Text.Trim() + "'";
            //}

            DunLibrary.Organization.Organization org = cmbCompany.SelectedItem as DunLibrary.Organization.Organization;

            if (org != null && org.Parent != null)
            {
                // where += " and c.BranchCompany.Id=" + org.Id;
                where += string.Format(" and (c.BranchCompany.Id = {0} or c.BranchCompany.FullNumber like '{1}.%' )",
                    org.Id, org.FullNumber);
            }

            DunLibrary.User.User u = cmbOper.SelectedItem as DunLibrary.User.User;
            if (u != null)
            {
                where += " and c.Oper.Id=" + u.Id;
            }

            DunLibrary.Dun.ControlType ct = cmbControlType.SelectedItem as DunLibrary.Dun.ControlType;

            if (ct != null)
            {
                where += " and c.ControlType.Id=" + ct.Id;
            }

            hql += where;

            //查询金额总和的hql
            totalAmountHql = "select sum(TotalAmount)" + hql;

            queryCondition = new QueryCondition();

            queryCondition.HQL = "select c " + hql;
            queryCondition.TotalHQL = "select count(c) " + hql;

            queryCondition.MaxResults = PageSize;
            
        }

        private void LoadCompany()
        {



            IList<DunLibrary.Organization.Organization> ls;

            if (AppGlobal.CurrentUser.Organization.Parent == null)//表示总公司
            {
                Action<IList<DunLibrary.Organization.Organization>> getOrgCallBack = (IList<DunLibrary.Organization.Organization> orgs) =>
                {

                    ls = orgs;
                    cmbCompany.ItemsSource = ls;
                    cmbCompany.IsEnabled = true;
                };
                AppGlobal.GetOrganizations(getOrgCallBack);

            }
            else
            {
                ls = new List<DunLibrary.Organization.Organization>();
                ls.Add(AppGlobal.CurrentUser.Organization);
                cmbCompany.ItemsSource = ls;
                cmbCompany.SelectedItem = ls[0];
                cmbCompany.IsEnabled = false;
            }
        }

        /// <summary>
        /// 根据权限加载业务员
        /// </summary>
        private void LoadOpers()
        {
            IList<DunLibrary.User.User> users = null;

            if (RightManagement.VerifyRight(RightManagement.Right_View_All_Case))
            {
                UserService.UserServiceClient ser = new UserService.UserServiceClient();

                ser.GetListByHQLCompleted += (object sender, UserService.GetListByHQLCompletedEventArgs e) =>
                {
                    int totalCount = 0;
                    users = JsonSerializerHelper.JsonToEntities<DunLibrary.User.User>(e.Result, out totalCount);
                    cmbOper.ItemsSource = users;
                };
                string hql = null;

                if (AppGlobal.CurrentUser.Organization.Parent == null)//表示总公司
                    hql = "from User " + AppGlobal.CurrentUser.Organization.Id; //查询所有的用户(业务员)
                else
                    //这里有个问题，当层级超过2层的时候，不能查询子机构的用户
                    hql = "from User where Organization.Id=" + AppGlobal.CurrentUser.Organization.Id;//查询当前部门的业务员

                ser.GetListByHQLAsync(hql);
            }
            else
            {
                users = new List<DunLibrary.User.User>();
                users.Add(AppGlobal.CurrentUser);

                cmbOper.ItemsSource = users;
                cmbOper.SelectedIndex = 0;
                cmbOper.IsEnabled = false;
            }

        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rDataPager1_PageIndexChanged(object sender, Telerik.Windows.Controls.PageIndexChangedEventArgs e)
        {

            if (queryCondition != null)
            {
                queryCondition.FirstResult = e.NewPageIndex * PageSize;

                QueryPaging(queryCondition);
            }
        }

        private void ViewCase()
        {
            DunLibrary.Dun.Case acase = dgdCase.SelectedItem as DunLibrary.Dun.Case;

            if (acase != null)
            {
                CaseForm form = new CaseForm(acase);
                Tools.OpenWindow("任务详细信息", form, null, 900, 600);
            }
        }


        private void btnEdit_Click(object sender, RoutedEventArgs e)
        {
            ViewCase();
        }

    }
}
